package com.atguigu.gmall.item.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.feign.product.SkuInfoFeignClient;
import com.atguigu.gmall.item.service.SkuDetailService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.starter.cache.annotation.BizLockOptions;
import com.atguigu.starter.cache.annotation.BloomOptions;
import com.atguigu.starter.cache.annotation.GmallCache;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 钟涛
 * @version 1.0
 * @description: TODO
 * @date 2021/12/10 11:44
 */
@Service
public class SkuDetailServiceImpl implements SkuDetailService {
    @Autowired
    private SkuInfoFeignClient skuInfoFeignClient;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Qualifier("skuBloomFilte")
    @Autowired
    private RBloomFilter<Object> rBloomFilter;

    @Autowired
    private ThreadPoolExecutor executor;

    /**
     * 真正回源查库的方法
     * @param skuId
     * @return
     */
    @GmallCache(cacheKey = RedisConst.SKUKEY_PREFIX + "#{#arg[0]}",
    lockOptions = @BizLockOptions(
            lockTime = 3,
            bizTime = 6
    ),
    bloomOptions = @BloomOptions(
            bloomName = "sku-bloom",
            checkExpression = "#{#arg[0]}"
    ))
    @Override
    public Map<String, Object> getSkuDetails(Long skuId) {
        Map<String,Object> map = new HashMap<>();
        /**
         * 1、categoryView: 三级分类信息
         * 2、skuInfo: (skuImageList) sku的基本信息
         * 3、price： 商品价格(实时查询)
         * 4、spuSaleAttrList: spu销售属性列表
         * 5、valuesSkuJson: 保存一对销售属性组合对应是那个商品
         */
        //1. 当前sku的基本信息
        SkuInfo skuInfo = skuInfoFeignClient.getSkuInfo(skuId);

        //2. 获取当前sku的三级分类信息
        BaseCategoryView categoryView = skuInfoFeignClient.getCategoryView(skuInfo.getCategory3Id());
        //3. 获取当前sku的所有图片信息
        List<SkuImage> skuImages = skuInfoFeignClient.getSkuImages(skuId);
        //4. 获取当前sku的价格
        BigDecimal price = skuInfoFeignClient.getSkuPriceBySkuId(skuId);

        //5. 获取当前sku对应spu的所有销售属性及其值，并标明当前sku所选的销售属性值
        List<SpuSaleAttr> saleAttrValues = skuInfoFeignClient.getSpuSaleAttrBySkuIdAndSpuId(skuId, skuInfo.getSpuId());

        //6. TODO  valuesSkuJson   保存一对销售属性组合对应是那个商品
        Map<String, String> valuesSkuJson = skuInfoFeignClient.getValuesSkuJson(skuInfo.getSpuId());
        skuInfo.setSkuImageList(skuImages);
        map.put("skuInfo",skuInfo);
        map.put("categoryView",categoryView);
        map.put("price",price);
        map.put("spuSaleAttrList",saleAttrValues);
        map.put("valuesSkuJson",valuesSkuJson);
        return map;
    }



    @GmallCache(cacheKey = RedisConst.SKUKEY_PREFIX + "#{#arg[0]}",
            lockOptions = @BizLockOptions(
                    lockTime = 3,
                    bizTime = 6
            ),
            bloomOptions = @BloomOptions(
                    bloomName = "sku-bloom",
                    checkExpression = "#{#arg[0]}"
            ))
    @Override
    public Map<String, Object> getSkuDetailsWithAsync(Long skuId) {
        Map<String,Object> map = new HashMap<>();
        //1. 当前sku的基本信息
        CompletableFuture<SkuInfo> skuInfoFuture = CompletableFuture.supplyAsync(() -> {

            SkuInfo skuInfo = skuInfoFeignClient.getSkuInfo(skuId);
            map.put("skuInfo",skuInfo);
            System.out.println("查询sku基本信息的线程名为---->"+Thread.currentThread().getName()+"结果为=>"+skuInfo);
            return skuInfo;
        }, executor);

        //2. 获取当前sku的三级分类信息
        CompletableFuture<Void> categoryView1 = skuInfoFuture.thenAcceptAsync((skuInfo) -> {
            BaseCategoryView categoryView = skuInfoFeignClient.getCategoryView(skuInfo.getCategory3Id());
            map.put("categoryView", categoryView);
//            System.out.println("查询当前sku的三级分类信息的线程名为---->" + Thread.currentThread().getName()+"结果为=>"+categoryView);
        }, executor);


        //3. 获取当前sku的所有图片信息
        CompletableFuture<Void> voidCompletableFuture = skuInfoFuture.thenAcceptAsync((skuInfo) -> {
            List<SkuImage> skuImages = skuInfoFeignClient.getSkuImages(skuId);
            skuInfo.setSkuImageList(skuImages);
//            System.out.println("获取当前sku的所有图片信息的线程名为---->" + Thread.currentThread().getName()+"结果为=>"+skuImages);
        }, executor);

        //4. 获取当前sku的价格
        CompletableFuture<Void> price1 = CompletableFuture.runAsync(() -> {
            BigDecimal price = skuInfoFeignClient.getSkuPriceBySkuId(skuId);
            map.put("price", price);
//            System.out.println("获取当前sku的价格的线程名为---->" + Thread.currentThread().getName()+"结果为=>"+price);
        }, executor);


        //5. 获取当前sku对应spu的所有销售属性及其值，并标明当前sku所选的销售属性值

        CompletableFuture<Void> spuSaleAttrList = skuInfoFuture.thenAcceptAsync((skuInfo) -> {
            List<SpuSaleAttr> saleAttrValues = skuInfoFeignClient.getSpuSaleAttrBySkuIdAndSpuId(skuId, skuInfo.getSpuId());
            map.put("spuSaleAttrList", saleAttrValues);
//            System.out.println("获取当前sku对应spu的所有销售属性及其值的线程名为---->" + Thread.currentThread().getName() + "结果为=>" + saleAttrValues);
        }, executor);

        CompletableFuture<Void> valuesSkuJson1 = skuInfoFuture.thenAcceptAsync((skuInfo) -> {
            Map<String, String> valuesSkuJson = skuInfoFeignClient.getValuesSkuJson(skuInfo.getSpuId());
            map.put("valuesSkuJson", valuesSkuJson);
//            System.out.println("获取valuesSkuJson1的线程名为---->" + Thread.currentThread().getName()+"结果为=>"+valuesSkuJson);
        }, executor);


        CompletableFuture.allOf(skuInfoFuture,categoryView1,voidCompletableFuture,price1,spuSaleAttrList,valuesSkuJson1).join();
//        System.out.println("最后的结果为:"+map);
        return map;
    }

    /**
     * 首先从缓存开始查询数据的方法
     * @param skuId
     * @return
     */
    @Override
    public Map<String, Object> getSkuDetailFromCache(Long skuId) throws Exception {
        //准备数据

        ObjectMapper objectMapper = new ObjectMapper();
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId;
        String lockKey = RedisConst.LOCK_PREFIX + RedisConst.SKU_LOCK + skuId;  //lock:sku:
        RLock lock = redissonClient.getLock(lockKey);
        //1.先查缓存
        String cacheResult = stringRedisTemplate.opsForValue().get(cacheKey);
        if (cacheResult == null) {
            //缓存中没有
            boolean b = false;
            try{
                //准备加锁、回源查数据库
                b = lock.tryLock(3, 6, TimeUnit.SECONDS);
                if(b){//等锁成功
                    cacheResult = stringRedisTemplate.opsForValue().get(cacheKey);
                    Map<String,Object> data = null;
                    if(cacheResult == null){//缓存中还是没有
                        //首先问布隆过滤器
                        boolean contains = rBloomFilter.contains(skuId);
                        if(contains){//布隆返回的是true
                            data = this.getSkuDetails(skuId);
                            long ttl = RedisConst.INDEX_CACHE_TIMEOUT;
                            if(data == null){
                                ttl = RedisConst.nullValueTtl;
                            }
                            String jsonStr = objectMapper.writeValueAsString(data);
                            stringRedisTemplate.opsForValue().set(cacheKey,jsonStr,ttl,TimeUnit.SECONDS);
                            //放入缓存中
                        }else{//布隆返回的是false
                            data =  null;
                        }

                    }else{
                        //缓存中有
                        data =  objectMapper.readValue(cacheResult, new TypeReference<Map<String, Object>>() {
                        });
                    }
                    return data;
                }else{//等锁失败,直接再查一遍缓存
                    return objectMapper.readValue(stringRedisTemplate.opsForValue().get(cacheKey), new TypeReference<Map<String, Object>>() {
                    });
                }
            }finally {
                if(b){//加上了锁，才进行解锁操作
                    try{//有可能解了别人的锁，所以在这抑制一下异常
                        lock.unlock();
                    }catch (Exception e){

                    }
                }
            }

        }else{
            //缓存中有
            Map<String, Object> map = objectMapper.readValue(cacheResult, new TypeReference<Map<String, Object>>() {
            });
            return map;
        }
    }




}
